<template>
  <div class="member-container" v-loading.fullscreen.lock="loading">
    <div class="fe-page-header">
      <div class="fe-page-header__left">
        {{ isEdit ? $t('member.edit.title1') : $t('member.edit.title2') }}
      </div>
      <div class="fe-page-header__right">
          <el-button class="fe-page-header__button" type="plain-third" @click="handleBack">
            {{$t('common.base.back')}}
          </el-button>
          <el-button
            class="fe-page-header__button"
            type="primary"
            native-type="submit"
            @click="handleSave">
            {{$t('common.base.save')}}
          </el-button>
        </div>
    </div>

    <div class="form-builder-container">
      <MembersEditForm
        ref="membersEditForm"
        :fields="_memberFields"
        v-model="form"
        :is-edit="isEdit"
      />
    </div>
  </div>
</template>

<script>
import MembersEditForm from '@src/modules/member/components/MembersEditForm.vue';
import { getMemberFields } from '@src/modules/member/field.js';
import { createMember, getMemberDetails, updateMember } from '@src/api/Member';
import { openAccurateTab } from '@src/util/platform';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum';
import qs from '@src/util/querystring';
import _ from 'lodash';

export default {
  components: {
    MembersEditForm,
  },
  data() {
    return {
      memberFields: [],
      form: {
        points: '0',
        balance: '0',
        serviceFee: '0',
        authorizationLimit: '0',
      },
      loading: false,
    };
  },
  computed: {
    memberId() {
      const queryObject = qs.parse(window.location.search);
      return queryObject.id ?? '';
    },
    action() {
      return this.memberId ? 'edit' : 'create';
    },
    isEdit() {
      return this.action === 'edit';
    },
    _memberFields() {
      let fields = this.memberFields.filter(item => item.isEdit)
      if(this.action == 'edit') {
        let arr = ['pointsEffectTime', 'serviceFeeEffectTime']
        let disabledFieldsArr = ['limitEffectTime', 'mainLinkmanPhone', 'cardNo', 'authorizationLimit', 'customer']
        let fieldsArr = fields.filter(v => !(arr.includes(v.fieldName)))
        fields = fieldsArr.map(item => {
          if(!disabledFieldsArr.includes(item.fieldName)) {
            this.$set(item, 'disabled', true)
          }
          return item
        })
      }
      return fields
    }
  },
  async mounted() {
    const { memberFields } = await getMemberFields();
    this.memberFields = memberFields || [];

    if(this.isEdit) {
      await this.getMemberDetails()
      this.initEditFields()
    }
  },
  methods: {
    async getMemberDetails() {
      this.loading = true
      const { code, result } = await getMemberDetails({ id: this.memberId });
      if(code !== 0) return this.$message.error(this.$t('member.edit.title3'));
      this.handleConvertData(result);
    },
    handleConvertData(data) {
      try {
        let { customer, linkman, limitEffectTime, limitExpirationTime, balance=0, serviceFee=0, points=0, authorizationLimit=0 } = data
        this.form = _.cloneDeep(data)
        if (customer) {
          let customerArr = [customer]
          customer = customerArr.map(item => {
            return {
              value: item.id,
              label: item.name
            }
          })
        }

        if (linkman) {
          let linkmanArr = [linkman]
          linkman = linkmanArr.map(item => {
            return {
              id: item.id,
              name: item.name,
              value: item.id,
              label: item.name,
              phone: item.phone
            }
          })
        }
        this.form.customer = customer
        this.form.linkman = linkman
        this.form.balance = String(balance)
        this.form.serviceFee = String(serviceFee)
        this.form.points = String(points)
        this.form.authorizationLimit = String(authorizationLimit)
        this.form.limitEffectTime = [limitEffectTime, limitExpirationTime]
        this.loading = false
      }catch (error) {
        this.loading = false;
        console.error('fetch goods Detail error', error);
      } 
      
    },
    handleSave() {
      this.$refs.membersEditForm.validate().then(valid => {
        if (!valid) {
          return Promise.reject('validate fail.');
        }
        if (/[\u4E00-\u9FA5]/g.test(this.form.cardNo)) {
          return this.$message.error(this.$t('member.components.title8'));
        }
        if(this.isEdit && !this.form.cardNo) {
          return this.$message.error(this.$t('member.components.title7'));
        }
        this.loading = true
        this.handleData()
      });
    },
    handleData() {
      let params = {}
      let { cardNo='', points=0, balance=0, serviceFee=0, authorizationLimit=0, pointsEffectTime=[], serviceFeeEffectTime=[], limitEffectTime=[], customer=[], linkman=[],cardTypeId='',endTime='',enabled=0, customerId  } = this.form
      let linkmanArr = (linkman || []).map(item => {
        return {
            id: item.id,
            name: item.name,
            phone: item.phone
          }
      })
      params  = {
          cardNo,
          authorizationLimit,
          limitEffectTime: limitEffectTime[0] || '',
          limitExpirationTime: limitEffectTime[1] || '',
          linkman: linkmanArr[0] || {},
          cardTypeId,
          endTime,
          enabled
        }
      if(this.isEdit) {
          // 编辑模式选择了会员
        if (!customerId && customer?.[0]) {
          const value = customer[0]
          params.customer = {
            id: value.id,
            name: value.name,
            serialNumber: value.serialNumber
          }
        }
        this.handleEdit(params);
      }else {
        let customerArr = (customer || []).map(item => {
          return {
            id: item.id,
            name: item.name,
            serialNumber: item.serialNumber
          }
        })

        params  = {
          ...params,
          points, balance, serviceFee, 
          pointsEffectTime: pointsEffectTime[0] || '',
          pointsExpirationTime: pointsEffectTime[1]  || '',
          serviceFeeEffectTime: serviceFeeEffectTime[0]  || '',
          serviceFeeExpirationTime: serviceFeeEffectTime[1]  || '',
          customer: customerArr[0] || {},
        }
        this.handleSubmit(params);
      }
    },
    openDetailTab(memberId) {
      setTimeout(() => {
        let id = window.frameElement.dataset.id;
        this.$platform.closeTab(id);

        // this.handleBack();
        openAccurateTab({
          type: PageRoutesTypeEnum.PageMemberDetail,
          key: this.memberId || memberId,
          params: `id=${this.memberId || memberId}`,
        })

        let fromId = window.frameElement.getAttribute('fromid');
        this.$platform.refreshTab(fromId);
      }, 1000);
    },
    handleBack() {
      let id = window.frameElement.dataset.id;
      this.$platform.closeTab(id);
    },
    async handleEdit(params) {
      try {
        const { code,  message} = await updateMember({...params, id: this.memberId});

        if (code !== 0) {
          this.loading = false;
          return this.$message.error(message);
        }
        this.loading = false;
        this.$message.success(this.$t('member.edit.title4'));
        this.openDetailTab()
      } catch (error) {
        this.loading = false;
        console.error('fetch goods Detail error', error);
      }
    },
    async handleSubmit(params) {

      try {
        const { code, result, message} = await createMember(params);

        if (code !== 0) {
          this.loading = false;
          return this.$message.error(message);
        }
        this.loading = false;
        this.$message.success(this.$t('member.edit.title5'));
        this.openDetailTab(result)
      } catch (error) {
        this.loading = false;
        console.error('fetch goods Detail error', error);
      }
    },
    initEditFields() {
      const { customer } = this.form
      this.memberFields = this.memberFields.map( field =>{
        if (field.fieldName === 'customer') {
          field.disabled = !!customer
        }

        return field
      })
    }
  },
};
</script>

<style lang="scss" scoped>
body {
  padding: 10px;
  // overflow: auto;
}
.member-container {
  width: 100%;
  height: 100%;
  overflow: auto;
  background-color: #fff;
  border-radius: 4px;
}
.form-builder-container {
  height: calc(100% - 56px);
  padding: 10px 16px;
  overflow: auto;
}

.form-builder {
  margin: 0 auto;
  width: 700px;
  padding: 10px 0 0 10px;

  .input-and-btn {
    display: flex !important;
    flex-flow: row nowrap;

    .form-item,
    .form-text,
    .form-select,
    .biz-team-select {
      flex: 1;
    }

    .base-dist-picker {
      padding-right: 0;
    }

    button {
      margin-left: 10px;
    }
  }
}
</style>
